//
//  UserAccount.swift
//  Weibo19
//
//  Created by 城 on 15/11/10.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
//access_token
    var access_token:String?
    //expires_in
    var expires_in:NSTimeInterval = 0
    //uid
    var uid:String?
    //avatar_large
    var avatar_large:String?
    //name
    var name:String?
    //KVC赋值
    init(dict:[String:AnyObject]) {
        super.init()

        setValuesForKeysWithDictionary(dict)
        
    }
    //过滤KVC的数值方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    
    override var description: String {
        let keys = ["access_token","expires_in","uid","avatar_large","name"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    func saveObject(){
    //沙盒路劲
     let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
        //归档
        NSKeyedArchiver.archiveRootObject(self,toFile: path)
        
    print(path)
    }
   //swift的类方法是class 加上自己类的类型
    class func loadAccount()->UserAccount? {
    //沙盒路径
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
        print(path)
        //解档
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount{
//            print(account)
             return account
        }
        
        return nil
    }

    //实现两个方法,,设置解档属性
    required init?(coder aDecoder: NSCoder) {
       
        access_token = aDecoder.decodeObjectForKey("access_token")as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid")as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large")as? String
        name = aDecoder.decodeObjectForKey("name")as? String
   
    }
    //设置归档属性
    func encodeWithCoder(aCoder: NSCoder){
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(name, forKey: "name")
    }
    
    
}
